package yja.gzw.app.activity

import android.content.Intent
import android.media.MediaScannerConnection
import android.net.Uri
import android.os.Environment
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.lifecycle.Observer
import cn.jzvd.Jzvd
import yja.gzw.app.R
import yja.gzw.app.base.BaseActivity
import yja.gzw.app.databinding.ActivityQufabuBinding
import yja.gzw.app.model.UserData
import yja.gzw.app.viewmodel.Mainviewmodel
import yja.gzw.app.window.Chicun
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream
import java.net.URL
import java.net.URLConnection
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

class QufabuActivity :BaseActivity<Mainviewmodel, ActivityQufabuBinding>(R.layout.activity_qufabu){
    var shipianpath=""
    val chicun=Chicun()
    var path=""
    var file:File?=null
    var isxiazai=false

    var libiview= mutableListOf<View>()
    private fun downloadVideo(videoUrl: String) {
        Thread {
            try {
                val url = URL(videoUrl)
                val connection: URLConnection = url.openConnection()
                connection.connect()

                val input: InputStream = connection.getInputStream()

                val currentDateTime = LocalDateTime.now()
                val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss")
                val formattedDateTime = currentDateTime.format(formatter)

                 file = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES), "${formattedDateTime}downloaded_video.mp4")
                Log.e("视频地址", file?.path!!)
                val output = FileOutputStream(file)

                val data = ByteArray(4096)
                var count: Int
                while (input.read(data).also { count = it } != -1) {
                    output.write(data, 0, count)
                }

                output.flush()
                output.close()
                input.close()

                // 通知系统媒体库更新
                MediaScannerConnection.scanFile(this, arrayOf(file?.absolutePath), null) { path, uri ->
                    Handler(Looper.getMainLooper()).post {
                        Toast.makeText(this, "下载完成", Toast.LENGTH_SHORT).show()
                        isxiazai=true
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
                Handler(Looper.getMainLooper()).post {
                    Toast.makeText(this, "下载失败", Toast.LENGTH_SHORT).show()
                }
            }
        }.start()
    }

    override fun onStart() {
        super.onStart()
        if(UserData.Kuaishoushouquan){
            binding.bangding2.text="已授权"
        }else{
            binding.bangding2.text="绑定新账户"

        }
        if(UserData.bilishouquan){
            binding.bangding3.text="已授权"
        }else{
            binding.bangding3.text="绑定新账户"

        }

        if(UserData.shouquandouying){
            binding.bangding1.text="已授权"
            binding.bangding4.text="已授权"
        }else{
            binding.bangding1.text="绑定新账户"
            binding.bangding4.text="绑定新账户"
        }


    }
    override fun initView() {
        if(UserData.Kuaishoushouquan){
            binding.bangding2.text="已授权"
        }else{
            binding.bangding2.text="绑定新账户"

        }
        if(UserData.bilishouquan){
            binding.bangding3.text="已授权"
        }else{
            binding.bangding3.text="绑定新账户"

        }

        if(UserData.shouquandouying){
            binding.bangding1.text="已授权"
            binding.bangding4.text="已授权"
        }else{
            binding.bangding1.text="绑定新账户"
            binding.bangding4.text="绑定新账户"
        }





        binding.pintai.setOnClickListener {
          val intent=Intent(this,BasedingzhanghaoActivity::class.java)
            startActivity(intent)
        }



        chicun.chicun(binding.videoView,350,200)
        chicun.chicun(binding.xiazai,30,200)

        val ids =intent.getStringExtra("idss")

        val pingtai =intent.getStringExtra("pingtai")


       val listss= pingtai?.split(",")
        listss?.forEach { item ->

            if(item=="抖音"){
                libiview.add(binding.bangding1)
                binding.dyshow.visibility=View.VISIBLE
            }
            if(item=="快手"){
                libiview.add(binding.bangding2)
                binding.ksshow.visibility=View.VISIBLE
            }
            if(item=="西瓜视频"){
                libiview.add(binding.bangding3)
                binding.xgshow.visibility=View.VISIBLE
            }
            if(item=="bilibili"){
                libiview.add(binding.bangding4)
                binding.blshow.visibility=View.VISIBLE
            }
        }



        binding.fabu.setOnClickListener {
            var shshu=0
            for (view in libiview) {
                if(view is TextView){
                    if( view.text=="已授权"){
                        shshu++
                    }


                }

            }

            if(shshu!=libiview.size){
                Toast.makeText(this, "请先绑定平台", Toast.LENGTH_SHORT).show()
            }else{
                if(isxiazai){
                    val inten=Intent(this,WodezhanghuaActivity::class.java)
                    inten.putExtra("idid",ids)
                    inten.putExtra("paths",path)
                    UserData.files=file
                    startActivity(inten)
                }else{
                    Toast.makeText(this, "请先下载视频，才可以发布哦", Toast.LENGTH_SHORT).show()

                }





            }



        }



        viewmodel.onxiangqingwang(UserData.token,mapOf("order_id" to ids!!))

        binding.xiazai.setOnClickListener {
            if (shipianpath.isNotEmpty()) {
                Toast.makeText(this, "下载中请稍后。。。", Toast.LENGTH_SHORT).show()
                downloadVideo(shipianpath)


            } else {
                Toast.makeText(this, "视频链接为空", Toast.LENGTH_SHORT).show()
            }
              //  Log.e("视频链接",shipianpath)


        }

    }

    override fun dataObservese() {
        viewmodel.onxiangqing.observe(this, Observer {
            if(it.code==1){
                Log.e("发送视频数据",it.data.toString())
                //todo  视频链接
                shipianpath=it.data.video_url.toString()






                binding.videoView.setUp(it.data.video_url.toString(), "播放视频", Jzvd.SCREEN_WINDOW_NORMAL)
                binding. videoView.thumbImageView.setImageURI(Uri.parse("http://p.qpic.cn/videoyun/0/2449_43b6f696980311e59ed467f22794e792_1/640"));

                path=it.data.video_url.toString()
                binding.shipingbiaoti.text=it.data.title
                binding.fabumoshishow.text=it.data.content
                binding.huobiaoqi.text=it.data.need_title



            }else{
                Toast.makeText(this,it.msg, Toast.LENGTH_SHORT).show()
            }

        })



    }


}